/**
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 * This file is a part of the CANN Open Software.
 * Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
 * Please refer to the License for details. You may not use this file except in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 */

/**
 * @file main.cpp
 */
 #include <algorithm>
 #include <cstdint>
 #include <iostream>
 #include <vector>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <unistd.h>
 #include <fstream>
 #include <fcntl.h>
 
 #include "acl/acl.h"
 #include "aclnn_mul_mul_reduce_mean_d_twice.h"
 
 #define SUCCESS 0
 #define FAILED 1
 
 #define INFO_LOG(fmt, args...) fprintf(stdout, "[INFO]  " fmt "\n", ##args)
 #define WARN_LOG(fmt, args...) fprintf(stdout, "[WARN]  " fmt "\n", ##args)
 #define ERROR_LOG(fmt, args...) fprintf(stderr, "[ERROR]  " fmt "\n", ##args)
 
 #define CHECK_RET(cond, return_expr) \
     do {                             \
         if (!(cond)) {               \
             return_expr;             \
         }                            \
     } while (0)
 
 #define LOG_PRINT(message, ...)         \
     do {                                \
         printf(message, ##__VA_ARGS__); \
     } while (0)
 
 #include <sstream>
 #include <vector>
 
 bool ReadFile(const std::string &filePath, size_t fileSize, void *buffer, size_t bufferSize)
 {
     struct stat sBuf;
     int fileStatus = stat(filePath.data(), &sBuf);
     if (fileStatus == -1) {
         ERROR_LOG("failed to get file %s", filePath.c_str());
         return false;
     }
     if (S_ISREG(sBuf.st_mode) == 0) {
         ERROR_LOG("%s is not a file, please enter a file", filePath.c_str());
         return false;
     }
 
     std::ifstream file;
     file.open(filePath, std::ios::binary);
     if (!file.is_open()) {
         ERROR_LOG("Open file failed. path = %s", filePath.c_str());
         return false;
     }
 
     std::filebuf *buf = file.rdbuf();
     size_t size = buf->pubseekoff(0, std::ios::end, std::ios::in);
     if (size == 0) {
         ERROR_LOG("file size is 0");
         file.close();
         return false;
     }
     if (size > bufferSize) {
         ERROR_LOG("file size is larger than buffer size");
         file.close();
         return false;
     }
     buf->pubseekpos(0, std::ios::in);
     buf->sgetn(static_cast<char *>(buffer), size);
     fileSize = size;
     file.close();
     return true;
 }
 
 bool WriteFile(const std::string &filePath, const void *buffer, size_t size)
 {
     if (buffer == nullptr) {
         ERROR_LOG("Write file failed. buffer is nullptr");
         return false;
     }
 
     int fd = open(filePath.c_str(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWRITE);
     if (fd < 0) {
         ERROR_LOG("Open file failed. path = %s", filePath.c_str());
         return false;
     }
 
     auto writeSize = write(fd, buffer, size);
     (void) close(fd);
     if (writeSize != size) {
         ERROR_LOG("Write file Failed.");
         return false;
     }
 
     return true;
 }
 
 int64_t GetShapeSize(const std::vector<int64_t> &shape)
 {
     int64_t shapeSize = 1;
     for (auto i : shape) {
         shapeSize *= i;
     }
     return shapeSize;
 }
 
 int Init(int32_t deviceId, aclrtStream *stream)
 {
     // 固定写法，acl初始化
     auto ret = aclInit(nullptr);
     CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return FAILED);
     ret = aclrtSetDevice(deviceId);
     CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return FAILED);
     ret = aclrtCreateStream(stream);
     CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return FAILED);
 
     return SUCCESS;
 }
 
 template <typename T>
 int CreateAclTensor(const std::vector<T> &hostData, const std::vector<int64_t> &shape, void **deviceAddr,
                     aclDataType dataType, aclTensor **tensor)
 {
     auto size = GetShapeSize(shape) * sizeof(T);
     // 调用aclrtMalloc申请device侧内存
     auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
     CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return FAILED);
 
     // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上
     ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
     CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return FAILED);
 
     // 调用aclCreateTensor接口创建aclTensor
     *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_ND, shape.data(),
                               shape.size(), *deviceAddr);
     return SUCCESS;
 }
 
 int main(int argc, char **argv)
 {
     // 1. （固定写法）device/stream初始化, 参考acl对外接口列表
     int32_t deviceId = 0;
     aclrtStream stream;
     auto ret = Init(deviceId, &stream);
     CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return FAILED);
 
     // 2. 构造输入与输出
     std::vector<int64_t> inputShape = {90, 1024}; // 示例形状
     std::vector<int64_t> outputShape = {90, 1024};
 
     // 输入数据
     std::vector<aclFloat16> mul0_input0_host(inputShape[0] * inputShape[1]);
     std::vector<aclFloat16> mul0_input1_host(inputShape[0] * inputShape[1]);
     std::vector<aclFloat16> mul1_input0_host(1); // 标量
     std::vector<aclFloat16> add_y_host(1);       // 标量
     std::vector<aclFloat16> gamma_host(inputShape[1]); // gamma 和 beta 的形状与列数一致
     std::vector<aclFloat16> beta_host(inputShape[1]);
 
     // 输出数据
     std::vector<aclFloat16> output_host(outputShape[0] * outputShape[1]);
 
     size_t fileSize = 0;
 
     // 读取输入数据
     ReadFile("../input/mul0input0.bin", fileSize, mul0_input0_host.data(), mul0_input0_host.size() * sizeof(aclFloat16));
     ReadFile("../input/mul0input1.bin", fileSize, mul0_input1_host.data(), mul0_input1_host.size() * sizeof(aclFloat16));
     ReadFile("../input/mul1input0.bin", fileSize, mul1_input0_host.data(), mul1_input0_host.size() * sizeof(aclFloat16));
     ReadFile("../input/addy.bin", fileSize, add_y_host.data(), add_y_host.size() * sizeof(aclFloat16));
     ReadFile("../input/gamma.bin", fileSize, gamma_host.data(), gamma_host.size() * sizeof(aclFloat16));
     ReadFile("../input/beta.bin", fileSize, beta_host.data(), beta_host.size() * sizeof(aclFloat16));
 
     INFO_LOG("Set input success");
 
     // 创建输入张量
     aclTensor *mul0_input0_tensor = nullptr, *mul0_input1_tensor = nullptr;
     aclTensor *mul1_input0_tensor = nullptr, *add_y_tensor = nullptr;
     aclTensor *gamma_tensor = nullptr, *beta_tensor = nullptr;
     aclTensor *output_tensor = nullptr;
 
     void *mul0_input0_device = nullptr, *mul0_input1_device = nullptr;
     void *mul1_input0_device = nullptr, *add_y_device = nullptr;
     void *gamma_device = nullptr, *beta_device = nullptr;
     void *output_device = nullptr;
 
     CreateAclTensor(mul0_input0_host, inputShape, &mul0_input0_device, aclDataType::ACL_FLOAT16, &mul0_input0_tensor);
     CreateAclTensor(mul0_input1_host, inputShape, &mul0_input1_device, aclDataType::ACL_FLOAT16, &mul0_input1_tensor);
     CreateAclTensor(mul1_input0_host, {1}, &mul1_input0_device, aclDataType::ACL_FLOAT16, &mul1_input0_tensor);
     CreateAclTensor(add_y_host, {1}, &add_y_device, aclDataType::ACL_FLOAT16, &add_y_tensor);
     CreateAclTensor(gamma_host, {inputShape[1]}, &gamma_device, aclDataType::ACL_FLOAT16, &gamma_tensor);
     CreateAclTensor(beta_host, {inputShape[1]}, &beta_device, aclDataType::ACL_FLOAT16, &beta_tensor);
 
     // 创建输出张量
     CreateAclTensor(output_host, outputShape, &output_device, aclDataType::ACL_FLOAT16, &output_tensor);
 
     // 调用函数
     uint64_t workspaceSize = 0;
     aclOpExecutor *executor = nullptr;
 
     INFO_LOG("Calling aclnnMulMulReduceMeanDTwiceGetWorkspaceSize...");
     ret = aclnnMulMulReduceMeanDTwiceGetWorkspaceSize(mul0_input0_tensor, mul0_input1_tensor, mul1_input0_tensor, add_y_tensor,
     gamma_tensor, beta_tensor, output_tensor, &workspaceSize, &executor);
 
     if (ret != ACL_SUCCESS) {ERROR_LOG("aclnnMulMulReduceMeanDTwiceGetWorkspaceSize failed. ERROR: %d", ret);
         return FAILED;}
 
     INFO_LOG("Workspace size: %lu", workspaceSize);
 
     void *workspaceAddr = nullptr;
     if (workspaceSize > 0) {
         ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
         CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return FAILED);
     }
 
     // 执行算子
     ret = aclnnMulMulReduceMeanDTwice(workspaceAddr, workspaceSize, executor, stream);
     CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMulMulReduceMeanDTwice failed. ERROR: %d\n", ret); return FAILED);
 
     // 同步流
     ret = aclrtSynchronizeStream(stream);
     CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return FAILED);
 
     // 获取输出数据
     ret = aclrtMemcpy(output_host.data(), output_host.size() * sizeof(aclFloat16),
                       output_device, output_host.size() * sizeof(aclFloat16), ACL_MEMCPY_DEVICE_TO_HOST);
     CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return FAILED);
 
     // 写入输出数据
     WriteFile("../output/output.bin", output_host.data(), output_host.size() * sizeof(aclFloat16));
     INFO_LOG("Write output success");
 
     // 释放资源
     aclDestroyTensor(mul0_input0_tensor);
     aclDestroyTensor(mul0_input1_tensor);
     aclDestroyTensor(mul1_input0_tensor);
     aclDestroyTensor(add_y_tensor);
     aclDestroyTensor(gamma_tensor);
     aclDestroyTensor(beta_tensor);
     aclDestroyTensor(output_tensor);
 
     aclrtFree(mul0_input0_device);
     aclrtFree(mul0_input1_device);
     aclrtFree(mul1_input0_device);
     aclrtFree(add_y_device);
     aclrtFree(gamma_device);
     aclrtFree(beta_device);
     aclrtFree(output_device);
 
     if (workspaceSize > 0) {
         aclrtFree(workspaceAddr);
     }
 
     aclrtDestroyStream(stream);
     aclrtResetDevice(deviceId);
     aclFinalize();
 
     return SUCCESS;
 }
 